package qrcode

import (
	"fmt"
	"gitee.com/injoyai/goutil/oss/file"
	"gitee.com/injoyai/goutil/oss/img"
	"image"
	"image/color"
	"os"

	"github.com/skip2/go-qrcode"
	qrcode2 "github.com/tuotoo/qrcode"
)

func Bytes(data string, color ...color.Color) ([]byte, error) {
	qr, err := qrcode.New(data, qrcode.Medium)
	if err != nil {
		return nil, err
	}
	if len(color) > 0 {
		qr.ForegroundColor = color[0]
	}
	return qr.PNG(256)
}

func Save(path, data string, color ...color.Color) error {
	bytes, err := Bytes(data, color...)
	if err != nil {
		return err
	}
	return file.New(path, bytes)
}

func Bytes2(name, data string, colors ...color.Color) ([]byte, error) {
	bs, err := Bytes(data, colors...)
	if err != nil {
		return nil, err
	}
	return img.NewImage(256, 285, color.White).WriteBytes(bs).WriteContent(name, image.Point{
		X: 20,
		Y: 270,
	}).Bytes()
}

func Save2(path, data string, color ...color.Color) error {
	name := file.NewPath(path).NamePrefix()
	bytes, err := Bytes2(name, data, color...)
	if err != nil {
		return err
	}
	return file.New(path, bytes)
}

func Decode(path string) (string, error) {
	fi, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer fi.Close()
	qrmatrix, err := qrcode2.Decode(fi)
	if err != nil {
		return "", err
	}
	fmt.Println([]byte(qrmatrix.Content))
	return qrmatrix.Content, nil
}
